package array;

/**
 * 数组的增删改查
 */
public class MyArrayDemo {

    public static void main(String[] args) {
        MyArray my = new MyArray(6);
        my.add(1);
        my.add(2);
        my.add(3);
        my.insert(4,3);
        my.insert(5,4);
        my.list();
    }


}

class MyArray {

    private int[] arr;
    private int size;
    private int capacity;

    public MyArray(int capacity) {
        this.arr = new int[capacity];
        this.capacity = capacity;
    }

    public boolean isFull() {
        if (size == arr.length) {
            return false;
        }
        return true;
    }

    //查看数组中的元素
    public void list() {
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }

    //添加元素
    public void add(int element) {
        isFull();
        arr[size] = element;
        size++;
    }

    //在指定位置添加元素
    //todo 如果没有顺序添加元素 则会有问题??
    public void add(int element, int index) {
        if (index < 0 || index > capacity){
            throw new RuntimeException("插入的索引有误");
        }
        for (int i = 0; i < arr.length-1; i++) {
            if (i >= index){
                arr[i+1] = arr[i];
            }
        }
        arr[index] = element;
        size++;
    }

    public void insert(int element,int index){
        if (index<0 ||index>capacity){
            throw new RuntimeException("插入的索引有误！");
        }
        for (int i = index+1; i < arr.length-1; i++) {
            arr[i] = arr[i+1];
        }
            arr[index] = element;
            size++;
    }


}
